package com.coolingme.register05.enum01;

import java.lang.reflect.Constructor;

/**
 * 反射破坏枚举单例模式测试
 *
 * @author wangyue
 * @date 2020/9/29 15:28
 */
public class ReflectTest {

    public static void main(String[] args) {
        try {
            //
            Class clazz = EnumSingleton.class;

            // 获取构造方法，枚举类型为protect的构造方法
            /*
            protected Enum(String name, int ordinal) {
                this.name = name; this.ordinal = ordinal;
            }
             */
            Constructor constructor = clazz.getDeclaredConstructor(String.class, int.class);

            // 强吻
            constructor.setAccessible(true);

            /*
            会报 java.lang.IllegalArgumentException: Cannot reflectively create enum objects
                at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
                at com.coolingme.register05.enum01.ReflectTest.main(ReflectTest.java:29)

            JDK 源码，进入 Constructor 的 newInstance()方法中做了强制性的判断，如果修饰符是 Modifier.ENUM 枚举类型， 直接抛出异常。

            代码如下：if ((clazz.getModifiers() & Modifier.ENUM) != 0)
                        throw new IllegalArgumentException("Cannot reflectively create enum objects");
             */
            EnumSingleton instance = (EnumSingleton) constructor.newInstance("joey", 001);
            System.out.println(instance);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
